// 审核新闻页面
import { Button, message, Table,Tag } from 'antd'
import axios from 'axios'
import React,{useEffect,useState} from 'react'

export default function Audit() {
    const [dataSource, setdataSource] = useState([])
    // 获取当前用户信息
    const {roleId,region,username}=JSON.parse(localStorage.getItem("token"))
    // 获取当前身份需要审核的新闻
    useEffect(() => {
        axios.get(`/news?auditState=1&_expand=category`).then(res=>{
            const list=res.data
            setdataSource(roleId===1 ? list:[
                ...list.filter(item=>item.author===username),
                ...list.filter(item=>item.region===region && item.roleId===3)
            ]);
        }
        )
    }, [roleId,region,username])
    // console.log(dataSource);

    const columns = [
        {
            // 列表标题
          title: '新闻标题',
        //   列表内容名称
          dataIndex: 'title',
          render:(title,item)=>{
              return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
          }
        },
        {
          title: '作者',
          dataIndex: 'author',
        },
        {
            title: '新闻分类',
            dataIndex: 'category',
            render:(category)=>{
                return <div>{category.title}</div>
            }
        },
        {
            title: '审核状态',
            dataIndex: 'auditState',
            render:(auditState)=>{
                const colorList=["",'orange','green','red']
                const auditList=["草稿箱","审核中","已通过","未通过"]
                return <Tag color={colorList[auditState]}>{auditList[auditState]}</Tag>
            }
        },
        {
            title:'操作',
            render:(item)=>{
                return (
                    <div>
                        {/* 撤销新闻按钮 */}
                        <Button  className='rightMargin' type="primary" onClick={()=>handleAudit(item,2,1)}>通过</Button>
                        <Button danger onClick={()=>handleAudit(item,3,0)}>驳回</Button>
                    </div>
                )
            }
        }
      ];

      const handleAudit=(item,auditState,publishState)=>{
        setdataSource(dataSource.filter(data=>data.id!==item.id))
        axios.patch(`/news/${item.id}`,{
            auditState:auditState,
            publishState:publishState
        }).then(res=>{
            if(auditState===2){
                message.success('已通过')
            }else{
                message.info('已驳回')
            }
        })
      }
    
    return (
        <div>
            <Table dataSource={dataSource} columns={columns}
            pagination={{
                pageSize:5
            }}
            rowKey={item=>item.id}/>
        </div>
    )
}
